package com.mall.security;

import com.central.common.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出处理器
 */
@Component
public class TokenLogoutHandler implements LogoutHandler {

    @Autowired
    private TokenManager tokenManager ;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper ;


    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
        if (token != null) {
            String username = tokenManager.getUserInfoFromToken(token);//根据token解析用户名
            redisTemplate.boundHashOps("permission").delete(username);
            redisTemplate.delete(username);
        }
        try {
            ResponseUtil.responseSucceed(objectMapper,response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
